<?php
/***
* @version $Id: index.php 336 2007-01-23 08:12:56Z flexiondotorg $
* @copyright (c) 2006 - 2007 Flexion.Org
*            (c) 2004 - 2006 OXPUS < webmaster@oxpus.de > (Karsten Ude) http://www.oxpus.de
*            (c) 2004 - 2006 CyberAlien (http://www.phpbbstyles.com)
*            (c) 2004 - 2005 Project Minerva
*            (c) 2003             Nivisec (support@nivisec.com) http://www.nivisec.com
*            (c) 2001 - 2006 phpBB Group
* @license   http://opensource.org/licenses/gpl-license.php GNU Public License
***/

define('IN_R3BORN', true);

//
// Load default header
//
//
$root_path = "./../";
$phpEx = substr(strrchr(__FILE__, '.'),	1);
$no_page_header = TRUE;
require('./pagestart.' . $phpEx);

### R3-born - ADD (Module Engine)
#
//We we have a requested module then run it.
if ($mvReqModuleName != '')
{
	$mvModuleName = $mvReqModuleName;
	$mvModuleFile = get_var('file', '');
	$mvModule_root_path = $root_path . 'modules/' . $mvModuleName . '/';

	//If the requested module file exists, use it.
	if (@file_exists($mvModule_root_path . 'admin/' . $mvModuleFile . '.' . $phpEx))
	{
		$mvModuleTemplates = $mvModules[$mvModuleName]['templates'];
		include($mvModule_root_path . 'admin/' . $mvModuleFile . '.' . $phpEx);
		exit;
	}
	else
	{
		// Could not find the requested module and file.
		$mvModuleTemplates = array();
		$mvModuleName =	'';
		$mvModuleFile =	'';
		$mvModule_root_path = '';
	}
}
else
{
	// Could not find the requested module
	$mvModuleTemplates = array();
	$mvModuleName =	'';
	$mvModuleFile =	'';
	$mvModule_root_path = '';
}
#
### R3-born - END ADD (Module Engine)

//
// Generate relevant output
//
if( isset($_GET['pane']) && $_GET['pane'] == 'left' )
{
### R3-born - REMOVE (Original Code)
#
/*
	$dir = @opendir(".");

	$setmodules = 1;
	while( $file = @readdir($dir) )
	{
		if( preg_match("/^admin_.*?\." . $phpEx . "$/", $file) )
		{
			include('./' . $file);
		}
	}

	@closedir($dir);

	unset($setmodules);
*/
#
### R3-born - END REMOVE

### R3-born - ADD (Jnr. Admin)
#
	$jr_admin_userdata = jr_admin_get_user_info($userdata['user_id']);

	$module = array();
	$module	= jr_admin_get_module_list($jr_admin_userdata['user_jr_admin']);
#
### R3-born - END ADD

	page_header_admin();

	$template->set_filenames(array(
		'body' => 'index_navigate.tpl')
	);

	$template->assign_vars(array(
		'U_SITE_INDEX' => append_sid('../index.' . $phpEx),
		'U_ADMIN_INDEX' => append_sid('index.' . $phpEx . '?pane=right'),
		'L_SITE_INDEX' => $lang['Main_index'],
		'L_ADMIN_INDEX' => $lang['Admin_Index'],
		'L_PREVIEW_SITE' => $lang['Preview_site']
		)
	);
### R3-born - ADD (Reduce ACP Navigation)
#
	$admin_id = $userdata['user_id'];

	$open_close_modul = get_var('oc','');
	$open_close = get_var('open_close','');

	if ( $open_close_modul != '')
	{
		if ( $open_close == 1 )
		{
			$sql = "INSERT INTO " . ADMIN_NAV_TABLE . " (user_id, modulname) VALUES ($admin_id, '$open_close_modul')";
		}
		else
		{
			$sql = "DELETE FROM " . ADMIN_NAV_TABLE . "
				WHERE user_id = $admin_id
				AND modulname = '$open_close_modul'";
		}

		if(!$result = $db->sql_query($sql))
		{
			message_die(GENERAL_ERROR, 'Could not set open/close status', '', __LINE__, __FILE__, $sql);
		}
	}

	// Read saved modules for admin
	$admin_nav_modul = array();

	$sql = "SELECT modulname FROM " . ADMIN_NAV_TABLE . "
		WHERE user_id = " . $userdata['user_id'] . "
		ORDER BY modulname";
	if($result = @$db->sql_query($sql))
	{
		while ( $row = $db->sql_fetchrow($result) )
		{
			$admin_nav_modul[] = $row['modulname'];
		}
	}
#
### R3-born - END ADD


### R3-born - REMOVE (Original Code)
#
/*
	ksort($module);

	while( list($cat, $action_array) = each($module) )
	{
		$cat = ( !empty($lang[$cat]) ) ? $lang[$cat] : preg_replace("/_/", " ", $cat);

		$template->assign_block_vars("catrow", array(
			"ADMIN_CATEGORY" => $cat)
		);

		ksort($action_array);

		$row_count = 0;
		while( list($action, $file)	= each($action_array) )
		{
			$row_class = ( !($row_count%2) ) ? 'row1' : 'row2';

			$action = ( !empty($lang[$action]) ) ? $lang[$action] : preg_replace("/_/", " ", $action);

			$template->assign_block_vars("catrow.modulerow", array(
				"ROW_CLASS" => $row_class,

				"ADMIN_MODULE" => $action,
				"U_ADMIN_MODULE" => append_sid($file))
			);
			$row_count++;
		}
	}
*/
#
### R3-born - END REMOVE

### R3-born - ADD (Jnr. Admin)
#
	@ksort($module);
	//Loop through and set up all the nice form	names, etc
	foreach	($module as	$cat =>	$module_array)
	{
		$admin_category_title = $cat;

		$cat = ( !empty($lang[$cat]) ) ? $lang[$cat] : preg_replace("/_/", " ", $cat);

		@ksort($module_array);

		if ( in_array($admin_category_title, $admin_nav_modul) )
		{
			$sign = '-';
			$oc_status = 0;
		}
		else
		{
			$sign = '+';
			$oc_status = 1;
		}

		$admin_category = '<a href="'.append_sid("index.$phpEx?pane=left&amp;oc=$admin_category_title&amp;open_close=$oc_status").'" class="mainmenu">'.$sign.'&nbsp;&nbsp;'.$cat.'</a>';

		$template->assign_block_vars("catrow", array(
			"ADMIN_CATEGORY" => $admin_category)
		);

		if ( $oc_status == 0 )
		{
			$i = 0;

			foreach	($module_array as $module_name => $data_array)
			{
				//Compile	our	module url with	lots of	options
				$module_url	= $data_array['filename'];
				$module_url	.= (preg_match("/^.*\.$phpEx\?/", $module_url))	? '&amp;' :	'?';
				$module_url	.= "sid=".$userdata['session_id']."&amp;module_md5=".$data_array['file_hash'];

				if (preg_match("~((admin)?[^\/\?&]*)\.$phpEx(?:[\?&]([^<>\s]*))?$~i", $module_url, $matches))
				{
					// $matches[1] = "admin_file"
					// $matches[2] = "admin"
					// $matches[3] = "mode=view&f=5"
					if ($matches[2]) //	Admin
					{
						reset($mvModules);
						foreach	($mvModules	as $name =>	$value)
						{
							/*
							if ($value['state']	!= 1 &&	$value['state']	!= 5)
							{
								continue;
							}
							*/
							if ($value['state'] == MODULE_ENABLED || $value['state'] == MODULE_DEFAULT)
							{
								if (in_array("$matches[1].$phpEx", $value['admin']))
								{
									$module_url	= $root_path . "admin/index.$phpEx?module=$name&file=$matches[1]"	. ($matches[3] ? "&$matches[3]" :	'');
									break;
								}
							}
						}
					}
				}

				$template->assign_block_vars("catrow.modulerow", array(
					'ROW_CLASS'	=> (++$i % 2) ?	'row1' : 'row2',
					'ADMIN_MODULE' => (isset($lang[$module_name])) ? $lang[$module_name] : preg_replace("/_/", ' ',	$module_name),
					'U_ADMIN_MODULE' =>	$module_url
					)
				);
			}
		}
	}
#
### R3-born - END ADD

	$template->pparse('body');

	page_footer_admin();
}
elseif( isset($_GET['pane']) && $_GET['pane'] == 'right' )
{
	page_header_admin();

	$template->set_filenames(array(
		'body' => 'index_body.tpl')
	);

	$template->assign_vars(array(
		'L_WELCOME' => $lang['Welcome_R3born'],
		'L_ADMIN_INTRO' => $lang['Admin_intro'],
		'L_SITE_STATS' => $lang['Site_stats'],
		'L_WHO_IS_ONLINE' => $lang['Who_is_Online'],
		'L_USERNAME' => $lang['Username'],
		'L_LOCATION' => $lang['Location'],
		'L_LAST_UPDATE' => $lang['Last_updated'],
		'L_IP_ADDRESS' => $lang['IP_Address'],
		'L_STATISTIC' => $lang['Statistic'],
		'L_VALUE' => $lang['Value'],
		'L_NUMBER_USERS' => $lang['Number_users'],
		'L_USERS_PER_DAY' => $lang['Users_per_day'],
		'L_BOARD_STARTED' => $lang['Board_started'],
		'L_AVATAR_DIR_SIZE' => $lang['Avatar_dir_size'],
		'L_DB_SIZE' => $lang['Database_size'],
		'L_SITE_LOCATION' => $lang['Site_Location'],
		'L_STARTED' => $lang['Login'],
		'L_GZIP_COMPRESSION' => $lang['Gzip_compression'])
	);

### R3-born - ADD
#
	loadHooks(getHooks('db_stat'));
	$hooks->execute('display_acp_db_stats');
#
### R3-born - END ADD

	$total_users = get_db_stat('usercount');
	$start_date = create_date($config['default_dateformat'], $config['board_startdate'], $config['board_timezone']);

	$boarddays = ( time() - $config['board_startdate'] ) / 86400;

	$users_per_day = sprintf("%.2f", $total_users / $boarddays);

	$avatar_dir_size = 0;

	if ($avatar_dir = @opendir($root_path . $config['avatar_path']))
	{
		while( $file = @readdir($avatar_dir) )
		{
			if( $file != '.' && $file != '..' )
			{
				$avatar_dir_size += @filesize($root_path . $config['avatar_path'] . '/' . $file);
			}
		}
		@closedir($avatar_dir);

		//
		// This bit of code translates the avatar directory size into human readable format
		// Borrowed the code from the PHP.net annoted manual, origanally written by:
		// Jesse (jesse@jess.on.ca)
		//
		if($avatar_dir_size >= 1048576)
		{
			$avatar_dir_size = round($avatar_dir_size / 1048576 * 100) / 100 . " MB";
		}
		else if($avatar_dir_size >= 1024)
		{
			$avatar_dir_size = round($avatar_dir_size / 1024 * 100) / 100 . " KB";
		}
		else
		{
			$avatar_dir_size = $avatar_dir_size . ' Bytes';
		}

	}
	else
	{
		// Couldn't open Avatar dir.
		$avatar_dir_size = $lang['Not_available'];
	}

	if($users_per_day > $total_users)
	{
		$users_per_day = $total_users;
	}

	//
	// DB size ... MySQL only
	//
	// This code is heavily influenced by a similar routine
	// in phpMyAdmin 2.2.0
	//
	if( preg_match("/^mysql/", SQL_LAYER) )
	{
		$sql = "SELECT VERSION() AS mysql_version";
		if($result = $db->sql_query($sql))
		{
			$row = $db->sql_fetchrow($result);
			$version = $row['mysql_version'];

			if( preg_match("/^(3\.23|4\.|5\.)/", $version) )
			{
				$db_name = ( preg_match("/^(3\.23\.[6-9])|(3\.23\.[1-9][1-9])|(4\.)|(5\.)/", $version) ) ? "`$dbname`" : $dbname;

				$sql = "SHOW TABLE STATUS
					FROM " . $db_name;
				if($result = $db->sql_query($sql))
				{
					$tabledata_ary = $db->sql_fetchrowset($result);

					$dbsize = 0;
					for($i = 0; $i < count($tabledata_ary); $i++)
					{
						if( $tabledata_ary[$i]['Type'] != "MRG_MyISAM" )
						{
							if( $table_prefix != "" )
							{
								if( strstr($tabledata_ary[$i]['Name'], $table_prefix) )
								{
									$dbsize += $tabledata_ary[$i]['Data_length'] + $tabledata_ary[$i]['Index_length'];
								}
							}
							else
							{
								$dbsize += $tabledata_ary[$i]['Data_length'] + $tabledata_ary[$i]['Index_length'];
							}
						}
					}
				} // Else we couldn't get the table status.
			}
			else
			{
				$dbsize = $lang['Not_available'];
			}
		}
		else
		{
			$dbsize = $lang['Not_available'];
		}
	}
	else if( preg_match("/^mssql/", SQL_LAYER) )
	{
		$sql = "SELECT ((SUM(size) * 8.0) * 1024.0) as dbsize
			FROM sysfiles";
		if( $result = $db->sql_query($sql) )
		{
			$dbsize = ( $row = $db->sql_fetchrow($result) ) ? intval($row['dbsize']) : $lang['Not_available'];
		}
		else
		{
			$dbsize = $lang['Not_available'];
		}
	}
	else
	{
		$dbsize = $lang['Not_available'];
	}

	if ( is_integer($dbsize) )
	{
		if( $dbsize >= 1048576 )
		{
			$dbsize = sprintf("%.2f MB", ( $dbsize / 1048576 ));
		}
		else if( $dbsize >= 1024 )
		{
			$dbsize = sprintf("%.2f KB", ( $dbsize / 1024 ));
		}
		else
		{
			$dbsize = sprintf("%.2f Bytes", $dbsize);
		}
	}

	$template->assign_vars(array(
		'NUMBER_OF_USERS' => $total_users,
		'START_DATE' => $start_date,
		'USERS_PER_DAY' => $users_per_day,
		'AVATAR_DIR_SIZE' => $avatar_dir_size,
		'DB_SIZE' => $dbsize,
		'GZIP_COMPRESSION' => ( $config['gzip_compress'] ) ? $lang['ON'] : $lang['OFF'])
	);
	//
	// End forum statistics
	//

	//
	// Get users online information.
	//
	$sql = "SELECT u.user_id, u.username, u.user_session_time, u.user_session_page, s.session_logged_in, s.session_ip, s.session_start, s.session_browser
		FROM " . USERS_TABLE . " u, " . SESSIONS_TABLE . " s
		WHERE s.session_logged_in = " . TRUE . "
			AND u.user_id = s.session_user_id
			AND u.user_id <> " . ANONYMOUS . "
			AND s.session_time >= " . ( time() - 300 ) . "
		ORDER BY u.user_session_time DESC";
	if(!$result = $db->sql_query($sql))
	{
		message_die(GENERAL_ERROR, "Couldn't obtain regd user/online information.", "", __LINE__, __FILE__, $sql);
	}
	$onlinerow_reg = $db->sql_fetchrowset($result);

	$sql = "SELECT session_page, session_logged_in, session_time, session_ip, session_start, session_browser
		FROM " . SESSIONS_TABLE . "
		WHERE session_logged_in = 0
			AND session_time >= " . ( time() - 300 ) . "
		ORDER BY session_time DESC";
	if(!$result = $db->sql_query($sql))
	{
		message_die(GENERAL_ERROR, "Couldn't obtain guest user/online information.", "", __LINE__, __FILE__, $sql);
	}
	$onlinerow_guest = $db->sql_fetchrowset($result);

	$reg_userid_ary = array();

	if( count($onlinerow_reg) )
	{
		$registered_users = 0;

		for($i = 0; $i < count($onlinerow_reg); $i++)
		{
			if( !in_array($onlinerow_reg[$i]['user_id'], $reg_userid_ary) )
			{
				$reg_userid_ary[] = $onlinerow_reg[$i]['user_id'];

				$username = color_user($onlinerow_reg[$i]['user_id'], $onlinerow_reg[$i]['username']);

				if( $onlinerow_reg[$i]['user_allow_viewonline'] || $userdata['user_level'] == ADMIN )
				{
					$registered_users++;
					$hidden = FALSE;
				}
				else
				{
					$hidden_users++;
					$hidden = TRUE;
				}

				$location =	$mvPages[$onlinerow_reg[$i]['user_session_page']]['name'];
				$location_url =	$mvPages[$onlinerow_reg[$i]['user_session_page']]['url'];

				$row_class = ( $registered_users % 2 ) ? 'row1' : 'row2';

				$reg_ip = decode_ip($onlinerow_reg[$i]['session_ip']);

				$template->assign_block_vars("reg_user_row", array(
					"ROW_CLASS" => $row_class,
					"USERNAME" => $username,
					"STARTED" => create_date($config['default_dateformat'], $onlinerow_reg[$i]['session_start'], $config['board_timezone']),
					"LASTUPDATE" => create_date($config['default_dateformat'], $onlinerow_reg[$i]['user_session_time'], $config['board_timezone']),
					"FORUM_LOCATION" => $location,

					"IP_ADDRESS" => $reg_ip,

					"U_WHOIS_IP" => "http://network-tools.com/default.asp?host=$reg_ip",
					"U_USER_PROFILE" => append_sid("admin_users.$phpEx?mode=edit&amp;" . POST_USERS_URL . "=" . $onlinerow_reg[$i]['user_id']),
					"U_FORUM_LOCATION" => (strpos($location_url, '?module')) ? '../' . substr($location_url, 0, -4) : '../' . $location_url
					)
				);
			}
		}

	}
	else
	{
		$template->assign_vars(array(
			"L_NO_REGISTERED_USERS_BROWSING" => $lang['No_users_browsing'])
		);
	}

	//
	// Guest users
	//
	if( count($onlinerow_guest) )
	{
		$guest_users = 0;

		for($i = 0; $i < count($onlinerow_guest); $i++)
		{
			$guest_userip_ary[] = $onlinerow_guest[$i]['session_ip'];
			$guest_users++;

			$location =	$mvPages[$onlinerow_guest[$i]['session_page']]['name'];
			$location_url =	$mvPages[$onlinerow_guest[$i]['session_page']]['url'];

			$row_class = ( $guest_users % 2 ) ? 'row1' : 'row2';

			$guest_ip = decode_ip($onlinerow_guest[$i]['session_ip']);

			// Search Bot Detection
			$bot_id = is_search_bot(decode_ip($onlinerow_guest[$i]['session_ip']), $onlinerow_guest[$i]['session_browser']);
			if ( $bot_id >=0 )
			{
				$guestname = $bot_style[$bot_name[$bot_id]];
				$block_var = 'bot_row';
			}
			else
			{
				$guestname = $lang['Guest'];
				$block_var = 'guest_user_row';
			}
			// END Search Bot Detection

			//$template->assign_block_vars('guest_user_row', array(
			$template->assign_block_vars($block_var, array(
				'ROW_CLASS' => $row_class,
				'USERNAME' => $guestname,
				'STARTED' => create_date($config['default_dateformat'], $onlinerow_guest[$i]['session_start'], $config['board_timezone']),
				'LASTUPDATE' => create_date($config['default_dateformat'], $onlinerow_guest[$i]['session_time'], $config['board_timezone']),
				'FORUM_LOCATION' => $location,
				'IP_ADDRESS' => $guest_ip,
				'U_WHOIS_IP' => "http://network-tools.com/default.asp?host=$guest_ip",
				'U_FORUM_LOCATION' => (strpos($location_url, '?module')) ? '../' . substr($location_url, 0, -4) : '../' . $location_url
				)
			);
		}

	}
	else
	{
		$template->assign_vars(array(
			'L_NO_GUESTS_BROWSING' => $lang['No_users_browsing'])
		);
	}

	// Check for new version
	$current_version = explode('.', $config['version']);
	$minor_revision = (int) $current_version[2];

	$errno = 0;
	$errstr = $version_info = '';

	// Change following two variables if you need to:
	// 24 hours cache timeout. change it to whatever you want

	$cache_update = 86400;
	$cache_file = '../cache/admin/core_update_' . $config['default_lang'] . '_' . $config['version'] . '.' . $phpEx; // file where to store cache

	$do_update = true;
	if(@file_exists($cache_file))
	{
		$last_update = 0;
		$version_info = '';
		@include($cache_file);
		if($last_update && !empty($version_info) && $last_update > (time() - $cache_update))
		{
			$do_update = false;
		}
		else
		{
			$version_info = '';
		}
	}

	if($do_update)
	{
		if ($fsock = @fsockopen('project-minerva.org.ru', 80, $errno, $errstr, 10))
		{
			@fputs($fsock, "GET /stuff/core.txt HTTP/1.1\r\n");
			@fputs($fsock, "HOST: project-minerva.org.ru\r\n");
			@fputs($fsock, "Connection: close\r\n\r\n");

			$get_info = false;
			while (!@feof($fsock))
			{
				if ($get_info)
				{
					$version_info .= @fread($fsock, 1024);
				}
				else
				{
					if (@fgets($fsock, 1024) == "\r\n")
					{
						$get_info = true;
					}
				}
			}
			@fclose($fsock);

			$version_info = explode("\n", $version_info);
			$latest_head_revision = (int) $version_info[0];
			$latest_minor_revision = (int) $version_info[2];
			$latest_version = (int) $version_info[0] . '.' . (int) $version_info[1] . '.' . (int) $version_info[2];

			if ($latest_head_revision == 0 && $minor_revision == $latest_minor_revision)
			{
				$version_info = '<p class="ok">' . $lang['Version_up_to_date'] . '</p>';
			}
			else
			{
				$version_info = '<p class="not_ok">' . $lang['Version_not_up_to_date'];
				$version_info .= '<br />' . sprintf($lang['Latest_version_info'], $latest_version) . ' ' . sprintf($lang['Current_version_info'], $config['version']) . '</p>';
			}
		}
		else
		{
			if ($errstr)
			{
				$version_info = '<p class="not_ok">' . sprintf($lang['Connect_socket_error'], $errstr) . '</p>';
			}
			else
			{
				$version_info = '<p>' . $lang['Socket_functions_disabled'] . '</p>';
			}
		}

		$version_info .= '<p>' . $lang['Mailing_list_subscribe_reminder'];

		if(@$f = fopen($cache_file, 'w'))
		{
			$search = array('\\', '\'');
			$replace = array('\\\\', '\\\'');
			fwrite($f, '<' . '?php $last_update = ' . time() . '; $version_info = \'' . str_replace($search, $replace, $version_info) . '\'; ?' . '>');
			fclose($f);
			@chmod($cache_file, 0777);
		}
	}

	if ($userdata['user_level'] == ADMIN)
	{
		$version_info .= ' ' . sprintf($lang['Check_blocks_modules'], '<a href="'.append_sid('admin_modules_version.' . $phpEx).'">', '</a>');
	}

	$version_info .= '</p>';

	$template->assign_vars(array(
		'VERSION_INFO'	=> $version_info,
		'L_VERSION_INFORMATION'	=> $lang['Version_information'])
	);

### R3-born - ADD (Jnr. Admin)
#
	jr_admin_make_info_box();
#
### R3-born - END ADD

	$template->pparse('body');

	page_footer_admin();

}
else
{
	//
	// Generate frameset
	//
	$template->set_filenames(array(
		'body' => 'index_frameset.tpl')
	);

	$template->assign_vars(array(
		'S_FRAME_NAV' => append_sid('index.' . $phpEx . '?pane=left'),
		'S_FRAME_MAIN' => append_sid('index.' . $phpEx . '?pane=right'))
	);

	header ("Expires: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
	header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");

	$template->pparse('body');

	$db->sql_close();
	exit;
}

?>